/* pdfGenerator.js */
import JsPDF from 'jspdf'
import html2canvas from 'html2canvas-pro'
import { invoke } from '@tauri-apps/api/core';
import '@/utils/simhei-normal.js'
/* ---------- 主函数 ---------- */
export function  generatePdf(elementId, filename = 'download', options = {}) {
    return new Promise(async (resolve, reject) => {
      const {
        orientation = 'p',
        unit = 'mm',
        format = 'a4',
        quality = 0.92,
        imageType = 'JPEG',
        autoPaging = true,
        watermarkText = '',
        watermarkOptions = {}
      } = options

      const element = document.getElementById(elementId)
      if (!element) return reject(new Error('找不到元素'))
      // const printId = document.getElementById('printId')
      // const pdfId = document.getElementById('pdfId')
      // // console.log('elementsToRemove',elementsToRemove)
      // if (pdfId) {
      //   pdfId.remove();
      // }
      // if (printId) {
      //   printId.remove();
      // }
      /* 备份并撑开高度 */
      const originalHeight = element.style.height
      const originalOverflow = element.style.overflowY
      element.style.height = 'auto'
      element.style.overflowY = 'visible'
      element.style.fontSize = '20px'

      /* 截图 */
      setTimeout(() => {
        html2canvas(element, { useCORS: true, scale: 1 })
          .then(async canvas => {
            /* 恢复样式 */
            element.style.height = originalHeight
            element.style.overflowY = originalOverflow

            /* 生成 PDF */
            const pdf = new JsPDF(orientation, unit, format)
            const pageWidth = pdf.internal.pageSize.getWidth()
            const pageHeight = pdf.internal.pageSize.getHeight()
            const imgWidth = pageWidth
            const imgHeight = (canvas.height * imgWidth) / canvas.width
            const imgData = canvas.toDataURL(`image/${imageType}`, quality)

            if (!autoPaging || imgHeight <= pageHeight) {
              pdf.addImage(imgData, imageType, 0, 0, imgWidth, imgHeight)
              if (watermarkText) {
                addWatermark(pdf, watermarkText, watermarkOptions, pageWidth, pageHeight)
              }
            } else {
              let y = 0
              const totalHeight = canvas.height
              const ratio = imgWidth / canvas.width
              while (y < totalHeight) {
                const sliceHeight = Math.min(totalHeight - y, pageHeight / ratio)
                const sliceCanvas = document.createElement('canvas')
                sliceCanvas.width = canvas.width
                sliceCanvas.height = sliceHeight
                const ctx = sliceCanvas.getContext('2d')
                ctx.drawImage(canvas, 0, y, canvas.width, sliceHeight, 0, 0, canvas.width, sliceHeight)
                pdf.addImage(sliceCanvas, imageType, 0, 0, imgWidth, sliceHeight * ratio)
                if (watermarkText) {
                  addWatermark(pdf, watermarkText, watermarkOptions, pageWidth, pageHeight)
                }
                y += sliceHeight
                if (y < totalHeight) pdf.addPage()
              }
            }

            // const pdfData = pdf.save(`${filename}.pdf`)
            const pdfName = `${filename}.pdf`
            const arrayBuffer = pdf.output('arraybuffer')
            const fileData = new Uint8Array(arrayBuffer);
            await invoke<string>('save_file_with_dialog', {
                fileData: Array.from(fileData),
                defaultFilename: pdfName
              })
            resolve(fileData);
          })
          .catch(err => {
            element.style.height = originalHeight
            element.style.overflowY = originalOverflow
            reject(new Error(`PDF生成失败: ${err}`))
          })
      }, 50)
    })
  }

  async function addWatermark(pdf, texts, options, pageWidth, pageHeight) {
    const {
      opacity = 0.1,
      fontSize = 14,
      color = '#999999',
      density = 2
    } = options

    pdf.saveGraphicsState()
    pdf.setGState(new pdf.GState({ opacity }))
    pdf.setFontSize(fontSize)
    pdf.setTextColor(color)
    pdf.setFont('simhei')

    const lineHeight = fontSize * 2.5
    const colWidth = pageWidth / density
    const rows = Math.ceil(pageHeight / lineHeight) * 2
    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < density; col++) {
        const x = col * colWidth + (row % 2 ? colWidth / 2 : 0)
        const y = row * lineHeight / 2
        texts.forEach((text, i) =>
          pdf.text(text, x, y + (i * lineHeight / texts.length), { angle: 45, align: 'left' })
        )
      }
    }
    pdf.restoreGraphicsState()
  }

